package com.deuwise.job.customquartz.base;
import com.deuwise.common.utils.SpringContextHolder;
import com.deuwise.job.entity.JobRunLogDo;
import com.deuwise.job.entity.TaskDo;
import com.deuwise.job.service.JobRunLogDoService;
import com.deuwise.job.service.TaskDoService;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Copyright
 *
 * @author chenwenchao
 * @date 2019/1/17 0017
 * Description:
 */
@Service
public class JobRunLogHelper {

    public  void getBaseRunLog(JobExecutionContext context, JobRunLogDo jobRunLogDo, Class<?> cla){
        String key = context.getJobDetail().getKey().getName();
        TaskDoService taskDoService = SpringContextHolder.getBean(TaskDoService.class);
        TaskDo taskDo= taskDoService.selectById(key);
        jobRunLogDo.setJobName(taskDo.getJobName());
        jobRunLogDo.setJobId(taskDo.getId());
        jobRunLogDo.setMethodClass(taskDo.getMethodName());
        jobRunLogDo.setRunTime(new Date());
        try {
            if (context.getNextFireTime() != null) {
                jobRunLogDo.setRunType(1);
                System.out.println(cla.getClass().getName()+"：下次执行时间=====" +
                        new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                                .format(context.getNextFireTime()) + "==============");
                jobRunLogDo.setNextRunTime(context.getNextFireTime());
            } else {
                //立即执行逻辑
                jobRunLogDo.setRunType(0);
                System.out.println(cla.getClass().getName()+"：立即执行测试=======================");
            }
            //执行run方法
            for(Method m :  cla.getMethods()) {
                if (m.getName().indexOf("run") == 0) {
                    System.out.println("method:" + m.getName());
                    System.out.println(m.invoke(cla.newInstance()));
                }
            }
            jobRunLogDo.setResults(1);
        } catch (Exception ex) {
            String exInfo="";
            if(ex.toString().length()>500){
                exInfo=ex.toString().substring(0,500);
            }else{
                exInfo=ex.toString();
            }
            jobRunLogDo.setResults(0);
            jobRunLogDo.setException(exInfo);
        }
        JobRunLogDoService jobRunLogDoService=SpringContextHolder.getBean(JobRunLogDoService.class);
        jobRunLogDoService.insert(jobRunLogDo);

    }
}
